<?php
namespace Backend\Controller;
use Think\Controller;
class BaseController extends Controller
{
    public function __construct() {
        // 先调用父类的构造方法
        parent::__construct();
        // 判断登录
        $id = session('Admin_Online');
        if(!$id)
            redirect(U('passport/login'));
        // 判断权限

    }

    /**
     * 格式化字符串返回数组
     * @param $str
     * @param $delimiter
     * @param string $char
     * @return array
     */
    public function strFormatToArray($str, $delimiter, $char = '') {
        if (empty($str)) return [];
        $str    = trim($str, $char);
        $data   = explode($delimiter, $str);
        return $data;
    }

    /**
     * 获取格式化后的日期时间[处理不连续时间 | 旧版本]
     * @param array $data
     * @return string
     */
    public function _getFormatDate($data = []) {
        if (empty($data)) return '';
        $data   = array_unique($data);
        $res    = [];

        foreach ($data as $k => $v) {
            $arr = explode(' ', $v);
            $res[$arr[0]]['time'][]     = strtotime($v);
            $res[$arr[0]]['timeStamp']  = strtotime($arr[0]);
        }

        foreach ($res as $k => $v) {
            sort($res[$k]['time']);
            $minIndex = array_search(min($res[$k]['time']), $res[$k]['time']);
            $maxIndex = array_search(max($res[$k]['time']), $res[$k]['time']);
            $res[$k]['time']['startTime']   = [$res[$k]['time'][$minIndex], date('Y-m-d H:i:s', $res[$k]['time'][$minIndex]) ];
            $res[$k]['time']['endTime']     = [$res[$k]['time'][$maxIndex], date('Y-m-d H:i:s', $res[$k]['time'][$maxIndex]) ];
        }

        return json_encode($res);
    }

    /**
     * 获取格式化后的日期时间[处理不连续时间]
     * @param string $str
     * @return string
     */
    public function getFormatDate($str = '') {
        if (!empty($str) && is_string($str)) {
            $res = [];
            $arrTime = explode(',', $str);

            foreach ($arrTime as $key => $value) {
                $date = explode(' ', $value);
                $time = explode('-', $date['1']);

                $startTime 	= $date['0'].' '.$time['0'];
                $endTime 	= $date['0'].' '.$time['1'];

                $res[$date['0']]['date']            = $value;
                $res[$date['0']]['timeStamp']		= strtotime($date['0']);
                $res[$date['0']]['startTime'][] 	= strtotime($startTime);
                $res[$date['0']]['startTime'][] 	= $startTime;
                $res[$date['0']]['endTime'][]		= strtotime($endTime);
                $res[$date['0']]['endTime'][]		= $endTime;
            }
        } else {
            return $str;
        }
        return json_encode($res);
    }

    /**
     * 获取投放中不连续的时间
     * @param array $data
     * @return array|string
     */
    public function getDateTimeToStr($data = []) {
        if (empty($data)) return $data;
        $res = '';

        foreach ($data as $k => $v) {
            $res .= empty($v['time']['startTime'][1]) ? '' : $v['time']['startTime'][1].'|';
            $res .= empty($v['time']['endTime'][1]) ? '' : $v['time']['endTime'][1].'|';
        }
        return $res;
    }

    /**
     * ThinkPHP3.2.3 不支持MongoDB 驱动，因项目需求 简单封装mongodb 统计方法
     * @param string $db
     * @param string $collection
     * @param array $filter
     * @return int
     */
    public function mongoCount($db = '', $collection = '', $filter = []) {
        $manager = new \MongoDB\Driver\Manager(C('MONGO_DB_DSN').$db);
        $filter = $filter;
        $options = [
            'projection' => [],
            "sort" => [1],
        ];
        $query = new \MongoDB\Driver\Query($filter, $options);
        $readPreference = new \MongoDB\Driver\ReadPreference(\MongoDB\Driver\ReadPreference::RP_PRIMARY);
        $result = $manager->executeQuery($db. '.' .$collection, $query, $readPreference)->toArray();

        return count($result);
    }


    /**
     * 发送HTTP请求方法
     * @param  string $url    请求URL
     * @param  array  $params 请求参数
     * @param  string $method 请求方法GET/POST
     * @return array  $data   响应数据
     */
    function curl_http($url, $params, $method = 'GET', $header = array(), $multi = false) {
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => $header
        );
        /* 根据请求类型设置特定参数 */
        switch(strtoupper($method)) {
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                // var_dump($opts[CURLOPT_URL]);exit;
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($error) throw new Exception('请求发生错误：' . $error);
        return $data;
    }
}